﻿using Janus.Cores.Application;
using Janus.Cores.Cacheing;
using Janus.Cores.Logger;
using Janus.Mes.WebClient.Common;
using Janus.Mes.WebClient.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace Janus.Mes.WebClient
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            CacheHelper.ClearCache("allValidModules");
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            Init();
        }
        protected void Application_Error(object sender, EventArgs e)
        {
            if (Context.IsCustomErrorEnabled)
            {
                var ex = Server.GetLastError();
                ShowCustomErrorPage(ex);
            }

        }

        private void Init()
        {
            AppRuntime.Init();
            //Services.Interface.Iindicator services = ServiceFactory.Create<Services.Interface.Iindicator>();
            //Services.Interface.Iindicator services = ServiceFactory.Create(typeof(Services.Interface.Iindicator)) as Services.Interface.Iindicator;
            // var result = services.FindOne(1);
            // Janus.UI.Expand.Register.Init();
            //RegisterServices.Init();
        }
        /// <summary>  
        /// 错误显示处理  
        /// </summary>  
        private void ShowCustomErrorPage(Exception exception)
        {
#if DEBUG
            throw exception;
#endif        
            LogManager.Default.Error(exception);
            var httpException = exception as HttpException ?? new HttpException(500, "服务器内部错误", exception);
            Response.Clear();
            var routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("fromAppErrorEvent", true);
            routeData.Values.Add("Error", exception);
            switch (httpException.GetHttpCode())
            {
                case 404:
                    routeData.Values.Add("action", "HttpError404");
                    break;
                case 500:
                    routeData.Values.Add("action", "HttpError500");
                    break;
                default:
                    routeData.Values.Add("action", "GeneralError");
                    routeData.Values.Add("httpStatusCode", httpException.GetHttpCode());
                    break;
            }

            Server.ClearError();
            IController controller = new ErrorController();
            controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }
    }
}
